package com.coderlin.filter;

import com.coderlin.pojo.User;
import com.coderlin.util.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <Description> <br>
 *
 * @author Coder_Lin<br>
 * @version 1.0<br>
 * @taskId: <br>
 * @createDate 2021/03/13 10:20 <br>
 * @see com.coderlin.filter <br>
 */
public class SysFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取SESSION,判断用户是否登录，没有SESSION则禁止访问jsp文件夹下的页面
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        if(user!=null){
            //允许其访问,固定操作，让程序能够继续运行
            filterChain.doFilter(servletRequest,servletResponse);

        }else{
            //对其重定向到Login页面,注意这里的重定向问题，如果没设置好路径将会导致循环重定向
            System.out.println(req.getContextPath());
            resp.sendRedirect("/error.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
